import os
import shutil
import zipfile
from flask import Flask, request, jsonify, send_from_directory
from werkzeug.utils import secure_filename

app = Flask(__name__)
BASE_DIR = os.path.abspath("file_storage")  # 文件存储根目录

# 确保基础目录存在
os.makedirs(BASE_DIR, exist_ok=True)


@app.route('/create_dir', methods=['POST'])
def create_directory():
    """创建目录接口"""
    data = request.get_json()
    if not data or 'path' not in data:
        return jsonify({"error": "Missing 'path' parameter"}), 400

    path = secure_filename(data['path'])
    full_path = os.path.join(BASE_DIR, path)

    if os.path.exists(full_path):
        return jsonify({"status": "Directory already exists"}), 200
    else:
        os.makedirs(full_path, exist_ok=True)
        return jsonify({"status": "Directory created"}), 201


@app.route('/upload', methods=['POST'])
def upload_file():
    """文件上传接口"""
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']
    target_dir = request.form.get('path', '')

    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    # 安全处理路径
    safe_dir = os.path.join(BASE_DIR, secure_filename(target_dir))
    if not os.path.exists(safe_dir):
        return jsonify({"error": "Directory does not exist"}), 404

    # 保存文件
    filename = secure_filename(file.filename)
    file_path = os.path.join(safe_dir, filename)
    file.save(file_path)

    # 生成下载链接
    download_url = f"/download/{os.path.join(target_dir, filename)}"

    # 获取文件信息
    file_info = {
        "filename": filename,
        "path": file_path.replace(BASE_DIR, "").lstrip('/'),
        "size": os.path.getsize(file_path),
        "download_url": download_url
    }

    return jsonify(file_info), 201


@app.route('/download/<path:filepath>')
def download_file(filepath):
    """文件下载接口"""
    safe_path = os.path.join(BASE_DIR, secure_filename(filepath))
    if not os.path.exists(safe_path):
        return jsonify({"error": "File not found"}), 404
    return send_from_directory(
        directory=os.path.dirname(safe_path),
        path=os.path.basename(safe_path),
        as_attachment=True
    )


@app.route('/list_dir', methods=['GET'])
def list_directory():
    """遍历目录接口"""
    target_dir = request.args.get('path', '')
    safe_dir = os.path.join(BASE_DIR, secure_filename(target_dir))

    if not os.path.exists(safe_dir):
        return jsonify({"error": "Directory not found"}), 404

    contents = []
    for item in os.listdir(safe_dir):
        item_path = os.path.join(safe_dir, item)
        is_dir = os.path.isdir(item_path)
        contents.append({
            "name": item,
            "type": "directory" if is_dir else "file",
            "size": os.path.getsize(item_path) if not is_dir else 0,
            "path": os.path.join(target_dir, item).replace('\\', '/')
        })

    return jsonify({
        "path": target_dir,
        "contents": contents
    })


@app.route('/unzip', methods=['POST'])
def unzip_file():
    """解压文件接口"""
    data = request.get_json()
    if not data or 'file_path' not in data or 'target_dir' not in data:
        return jsonify({"error": "Missing parameters"}), 400

    # 安全处理路径
    zip_path = os.path.join(BASE_DIR, secure_filename(data['file_path']))
    print(zip_path)
    target_dir = os.path.join(BASE_DIR, secure_filename(data['target_dir']))

    # 验证路径存在
    if not os.path.exists(zip_path):
        return jsonify({"error": "Zip file not found"}), 404
    if not os.path.exists(target_dir):
        return jsonify({"error": "Target directory not found"}), 404

    # 解压文件
    try:
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(target_dir)
        return jsonify({
            "status": "Success",
            "extracted_to": target_dir.replace(BASE_DIR, "").lstrip('/')
        }), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)